from app import db
from datetime import datetime

class SystemArchitecture(db.Model):
    __tablename__ = 'system_architectures'
    
    id = db.Column(db.Integer, primary_key=True)
    project_id = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=False)
    name = db.Column(db.String(128), nullable=False)
    architecture_type = db.Column(db.String(32), nullable=False)  # centralized, distributed, hybrid
    description = db.Column(db.Text)
    topology = db.Column(db.JSON)  # 系统拓扑结构
    components = db.Column(db.JSON)  # 系统组件配置
    communication = db.Column(db.JSON)  # 通信方式配置
    creator_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    project = db.relationship('Project', backref=db.backref('architectures', lazy=True))
    creator = db.relationship('User', backref=db.backref('architectures', lazy=True))
    
    def __init__(self, project_id, name, architecture_type, creator_id, description=None,
                 topology=None, components=None, communication=None):
        self.project_id = project_id
        self.name = name
        self.architecture_type = architecture_type
        self.creator_id = creator_id
        self.description = description
        self.topology = topology or []
        self.components = components or []
        self.communication = communication or []
    
    def __repr__(self):
        return f'<SystemArchitecture {self.name}>'
    
    def to_dict(self):
        return {
            'id': self.id,
            'project_id': self.project_id,
            'name': self.name,
            'architecture_type': self.architecture_type,
            'description': self.description,
            'topology': self.topology,
            'components': self.components,
            'communication': self.communication,
            'creator_id': self.creator_id,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        } 